/**
 * 
 */
package com.mobile2you.nci.android.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mobile2you.nci.android.R;
import com.mobile2you.nci.android.domain.News;

/**
 * @author JBromo
 * 
 */
public class ListNewsAdapter extends BaseAdapter {

	List<News> listNews = new ArrayList<News>();

	class CentreItemView extends LinearLayout implements Callback {
		TextView name;
		private final ImageView imageView;

		News centres;

		public CentreItemView(Context context, News centres) {
			super(context);
			LayoutInflater.from(context).inflate(R.layout.news_item_view, this,
					true);
			this.centres = centres;
			name = (TextView) findViewById(R.id.label_centre_item_name);
			imageView = (ImageView) findViewById(R.id.imageView1);
			name.setText(centres.getTitle());
			LoadImagePool.loadImage(getContext(), centres.getImageUrl(),
					new Handler(this), false);
			this.setTag(String.valueOf(centres.getImageUrl()));
		}

		@Override
		public boolean handleMessage(Message msg) {

			if (msg.obj != null) {
				Bitmap image = (Bitmap) msg.obj;
				imageView.setBackgroundDrawable(new BitmapDrawable(getContext()
						.getResources(), image));
				centres.setBitmap(image);

			}

			return false;
		}

		private void reuse(News centres) {
			name.setText(centres.getTitle());
			LoadImagePool.loadImage(getContext(), centres.getImageUrl(),
					new Handler(this), false);
		}

	}

	/**
	 * @param listNews
	 */
	public ListNewsAdapter(List<News> listNews) {
		this.listNews = listNews;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listNews.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return listNews.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		News centres = listNews.get(position);
		CentreItemView centreItemView = null;
		if (convertView != null
				&& convertView.getTag().toString()
						.equalsIgnoreCase(centres.getImageUrl())) {
			centreItemView = (CentreItemView) convertView;
			centreItemView.reuse(centres);
			return centreItemView;
		}
		return new CentreItemView(parent.getContext(), centres);
	}

}
